<template>
  <div>
    <el-dialog
        :title="!dataForm.id ? $t('handle.add') : $t('handle.update')"
        :close-on-click-modal="false"
        :visible.sync="visible">
    <div v-loading = loading>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item v-if="superAdmin==1 && addFlag" label="所属小区" prop="housingEstateId">
         <el-cascader style="width: 100%;" v-model="address" :options="options" :show-all-levels="true"  @active-item-change="getNodes" :props="props"></el-cascader>
      </el-form-item>
      <el-form-item v-if="updateFlag" label="所属小区" prop="housingEstateName">
        <el-input :disabled="true" v-model="dataForm.housingEstateName"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('form.userName')" prop="username">
        <el-input :disabled="updateFlag" v-model="dataForm.username"
         placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item v-if="addFlag" label="密码" prop="password">
        <el-input type="password" v-model="dataForm.password"
         placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item :label="$t('form.nickname')" prop="nickName">
        <el-input v-model="dataForm.nickName"
         placeholder="昵称"></el-input>
      </el-form-item>
      <el-form-item label="所属组织" prop="deptName">
        <el-input  v-model="dataForm.deptName"
         placeholder="所属组织" @focus="handleDept()" readonly></el-input>
         <input type="hidden" v-model="dataForm.deptId" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
          <el-select style="width: 100%;" class="filter-item" v-model="role" placeholder="请选择" multiple>
            <el-option v-for="item in rolesOptions" :key="item.roleId" :label="item.roleDesc" :value="item.roleId" :disabled="isDisabled[item.delFlag]">
              <span style="float: left">{{ item.roleDesc }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roleCode }}</span>
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item :label="$t('form.contactWay')" prop="phone">
        <el-input v-model="dataForm.phone"
         placeholder="联系方式"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          action="/clientauth/client/upload"
          :show-file-list="false"
          :on-error="handleError"
          :on-success="handleAvatarSuccess"
          :headers="headers"
          :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.avatar" :src="this.imgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div style="text-align:right;">
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
      <el-button v-if="show" type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
    </div>
    </div>
  </el-dialog>
  <el-dialog title="选择组织" :visible.sync="dialogDeptVisible">
    <el-tree class="filter-tree" :data="treeDeptData" :default-checked-keys="checkedKeys" check-strictly node-key="id" highlight-current ref="deptTree" :props="defaultProps" @node-click="getNodeData" default-expand-all>
    </el-tree>
  </el-dialog>
  <el-dialog title="选择组织" :visible.sync="dialogDeptVisible">
    <el-tree class="filter-tree" :data="treeDeptData" :default-checked-keys="checkedKeys" check-strictly node-key="id" highlight-current ref="deptTree" :props="defaultProps" @node-click="getNodeData" default-expand-all>
    </el-tree>
  </el-dialog>
 </div>
</template>
<script>
import Vue from "vue";
import { dateFormate, isMobile } from "@/utils/validate";
import { imgUrlHost } from '@/config/env';
import { curApp } from '@/config/env'
import {
  fetchDeptTree,
  deptAppRoleList,
  deptRoleList
} from "@/utils/dgBrain";
import {
  getOne,
  getTwo,
  getThree,
  getFour,
  getFive,
  getSix
} from "@/utils/questUtils";
export default {
  data() {
    // 严格的验证规则可以放到这里验证
    let checkCPhone = (rule, value, callback) => {
      if (value !== "") {
        if (isMobile(value)) {
          callback();
        } else {
          callback(new Error("手机格式不正确"));
        }
      } else {
        callback();
      }
    };
    let checkHousingEstate = (rule, value, callback) => {
      if (typeof this.address[this.address.length - 1] === "undefined") {
        callback(new Error("小区不能为空"));
      } else {
        callback();
      }
    };
    return {
      loading:false,
      isDisabled: {
        0: false,
        1: true
      },
      role: [],
      rolesOptions: [],
      treeDeptData: [],
      dialogDeptVisible: false,
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      imgUrl:"",
      headers: {
        Authorization: "Bearer " + Vue.cookie.get("access-token")
      },
      imgUrlHost:imgUrlHost,
      superAdmin: sessionStorage.getItem("superAdmin"),
      options: [],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      address: [],
      addFlag: false,
      updateFlag: false,
      show: true,
      visible: false,
      dataForm: {
        id: "",
        username: "",
        phone: "",
        dgUserId: "",
        avatar: "",
        housingEstateId: "",
        superAdmin: "2",
        deptName:"",
        deptId:"",
        housingEstateName: "",
        nickName:"",
      },
      // 验证Todo 其他的验证后续加上
      dataRule: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        role: [
          { required: true, message: "角色不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "组织不能为空", trigger: "blur" }
        ],
        housingEstateId: [
          { required: true, validator: checkHousingEstate, trigger: "blur" }
        ],
        phone: [{ validator: checkCPhone, trigger: "blur" }]
      }
    };
  },
  mounted() {},
  // 引入的组件
  components: {},
  created() {
    if (this.superAdmin == 1) {
      this.getOne();
    }

    // this.superAdmin = sessionStorage .getItem('superAdmin');
  },
  methods: {
    getNodeData(data) {
      this.dialogDeptVisible = false;
      this.dataForm.deptId = data.id;
      this.dataForm.deptName = data.name;
      deptAppRoleList(data.id,curApp).then(response => {
        this.rolesOptions = response.data;
      });
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data;
        this.dialogDeptVisible = true;
      });
    },
    // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
      if (val.length === 1) {
        // 获取省
        this.getTwo(val[0]);
      } else if (val.length === 2) {
        // 市
        this.getThree(val[0], val[1]);
      } else if (val.length === 3) {
        // 区
        this.getFour(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getFive(val[0], val[1], val[2], val[3]); //社区
      } else if (val.length === 5) {
        this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
      }
      //如果继续添加下级，类似这样继续添加即可
    },
    // 文件上传成功时调用
    handleAvatarSuccess(response, file) {
      //  this.dataForm.avatar = URL.createObjectURL(file.raw);
       this.imgUrl = imgUrlHost +  response.iconName;
       this.dataForm.avatar = response.iconName;
    },
    // 文件上传失败时调用
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      let fileFlag = false;
      if (isJPG || isPNG) {
        fileFlag = true;
      } else {
        this.$message.error("上传头像图片只能是 JPG 格式或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      /**************************** */
      const isSize = true;
      // const isSize = new Promise(function(resolve, reject) {
      //   let width = 750; // 限制图片尺寸为654X270
      //   let height = 279;
      //   let _URL = window.URL || window.webkitURL;
      //   let img = new Image();
      //   img.onload = function() {
      //     let valid = img.width === width && img.height === height;
      //     valid ? resolve() : reject();
      //   };
      //   img.src = _URL.createObjectURL(file);
      // }).then(
      //   () => {
      //     return file;
      //   },
      //   () => {
      //     this.$message.error("图片尺寸限制为750 x 279");
      //     return Promise.reject();
      //   }
      // );

      return fileFlag && isLt2M && isSize;
    },
    getUeditorContent(msg) {
      // this.dataForm.completeFlag = msg[0]
      this.dataForm.content = msg;
    },
    clearForm() {
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      })
      this.dataForm.username = '';
      this.dataForm.password = '';
      this.dataForm.phone = '';
      this.dataForm.dgUserId = '';
      this.dataForm.housingEstateName = '';
      this.dataForm.deptName = '';
      this.dataForm.deptId = '';
      this.dataForm.nickName = '';
      this.dataForm.avatar = '';
      this.rolesOptions = [];
      this.address = [];
      this.role= [];
    },
    init(id, show) {
      this.updateFlag = true;
      this.addFlag = false;
      this.show = show;
      this.visible = true;
      this.dataForm.id = id || 0;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      })
      if (typeof id == "undefined") {
        // 新增
        this.clearForm();
      }
      if (this.dataForm.id) {
        this.$http({
          url: `/dg-ic/ic/sys/user/info/${this.dataForm.id}`,
          method: "get",
          params: this.$http.adornParams()
        }).then(
          ({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.username = data.data.username;
              this.dataForm.phone = data.data.phone;
              this.dataForm.nickName = data.data.nickName;
              this.dataForm.dgUserId = data.data.dgUserId;
              this.dataForm.housingEstateName = data.data.housingEstateName;
              this.dataForm.avatar = data.data.avatar;
              this.imgUrl = imgUrlHost + data.data.avatar;
              this.dataForm.deptName =  data.data.deptName;
              this.dataForm.deptId = data.data.deptId;
              this.dataForm.roleList = data.data.roleList;
              this.role = [];
              for (var i = 0; i < this.dataForm.roleList.length; i++) {
                this.role[i] = this.dataForm.roleList[i].roleId;
              }
              deptAppRoleList(this.dataForm.deptId,curApp).then(response => {
                this.rolesOptions = response.data;
              });
            } else {
              this.$message.error(data.msg);
            }
          },
          error => {
            if (error.response.status === 403) {
              this.$message.error("你没有权限");
            } else {
              this.$message.error("系统错误，请联系管理员");
            }
          }
        );
      }
    },
    addinit(id, show) {
      this.updateFlag = false;
      this.getOne();
      this.addFlag = true;
      this.show = show;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      })
      this.clearForm();
      this.dataForm.username = "";
      this.dataForm.phone = "";
      this.dataForm.id = id || 0;
    },
    // 表单提交
    dataFormSubmit() {
      this.dataForm.role = this.role;
      this.$refs["dataForm"].validate(validate => {
        if (validate) {
          this.loading = true
          this.$http({
            url: `/dg-ic/ic/sys/user/${!this.dataForm.id ? "save" : "update"}`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              username: this.dataForm.username,
              nickName: this.dataForm.nickName,
              phone: this.dataForm.phone,
              password: this.dataForm.password,
              dgUserId: this.dataForm.dgUserId,
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id,
              avatar:this.dataForm.avatar,
              deptId:this.dataForm.deptId,
              role:this.role,
              housingEstateId:
                sessionStorage.getItem("superAdmin") == 1
                  ? this.address[this.address.length - 1]
                  : sessionStorage.getItem("thiscommunityId"), // 看是不是超管，时的话就给小区选择，否则就给他自身带的小区id
              superAdmin: this.dataForm.superAdmin
              // 后续的字段后续加上
            })
          }).then(
            ({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.loading = false
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
                this.loading = false
              }
            },
            error => {
              if (error.response.status === 403) {
                this.$message.error("你没有权限");
                this.loading = false
              } else {
                this.$message.error("系统错误，请联系管理员");
                this.loading = false
              }
            }
          );
        }
      });
    }
  }
};
</script>
